package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("DetectdetailRestController")
public class DetectdetailRestController extends CmiEmaController {

	/**
	 * Create a new Detectdetail entity
	 * 
	 */
	@RequestMapping(value = "/newDetectdetail", method = RequestMethod.POST)
	@ResponseBody
	public Object newDetectdetail(@RequestBody Detectdetail detectdetail) {
		detectdetailService.saveDetectdetail(detectdetail);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetail.getId()), 2));
	}

	@RequestMapping(value = "/restNewDetectdetail", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewDetectdetail(@RequestBody String detectdetailJson) {
		Detectdetail detectdetail = new Gson().fromJson(detectdetailJson, Detectdetail.class);
		appendReferences(detectdetail);
		detectdetailService.saveDetectdetail(detectdetail);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetail.getId()), 2));
	}

	@RequestMapping(value = "/saveDetectdetail", method = RequestMethod.PUT)
	@ResponseBody
	public Detectdetail saveDetectdetail(@RequestBody Detectdetail detectdetail) {
		detectdetailService.saveDetectdetail(detectdetail);
		return detectdetailDAO.findDetectdetailByPrimaryKey(detectdetail.getId());
	}

	@RequestMapping(value = "/restSaveDetectdetail", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveDetectdetail(@RequestBody String detectdetailJson) {
		Detectdetail detectdetail = new Gson().fromJson(detectdetailJson, Detectdetail.class);
		appendReferences(detectdetail);
		CmiPsonService cmiPsonService = new CmiPsonService();
		detectdetailService.saveDetectdetail(detectdetail);
		return JSONObject
				.parse(cmiPsonService.toJsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetail.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteDetectdetail/{detectdetailId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteDetectdetail(@PathVariable Integer detectdetailId) {
		Detectdetail detectdetail = detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId);
		detectdetailService.deleteDetectdetail(detectdetail);
	}

	@RequestMapping(value = "/restConfirmDeleteDetectdetails")
	@ResponseBody
	public Object restConfirmDeleteDetectdetails(@RequestBody Set<Integer> deleteDetectdetailsIds) {
		Set<Detectdetail> deleteDetectdetails = detectdetailDAO.findDetectdetailsByIds(deleteDetectdetailsIds);
		Set<Detectdetail> referencedDetectdetails = detectdetailService.loadReferenceDetectdetails(deleteDetectdetails);
		deleteDetectdetails.removeAll(referencedDetectdetails);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedDetectdetails);
		jsonObject.put("deleteEntitys", deleteDetectdetails);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteDetectdetails")
	@ResponseBody
	public Object restDeleteDetectdetails(@RequestBody Set<Detectdetail> deleteDetectdetails) {
		Iterator<Detectdetail> iterator = deleteDetectdetails.iterator();
		while (iterator.hasNext()) {
			Detectdetail currentDetectdetail = iterator.next();
			detectdetailService.deleteDetectdetail(currentDetectdetail);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listDetectdetails");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadDetectdetail/{detectdetailId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdetail(@PathVariable Integer detectdetailId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdetailDetect/{detectdetailId}/detect", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdetailDetect(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getDetect(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdetailFeature/{detectdetailId}/feature", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdetailFeature(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdetailUnit/{detectdetailId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdetailUnit(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadDetectdetailDetectmethod/{detectdetailId}/detectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadDetectdetailDetectmethod(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getDetectmethod(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Detectdetail detectdetail) {

		Detect detect = detectdetail.getDetect();
		if (detect != null)
			detectdetail.setDetect(detectService.findDetectByPrimaryKey(detect.getId()));

		Feature feature = detectdetail.getFeature();
		if (feature != null)
			detectdetail.setFeature(featureService.findFeatureByPrimaryKey(feature.getId()));

		Unit unit = detectdetail.getUnit();
		if (unit != null)
			detectdetail.setUnit(unitService.findUnitByPrimaryKey(unit.getId()));

		Detectmethod detectmethod = detectdetail.getDetectmethod();
		if (detectmethod != null)
			detectdetail.setDetectmethod(detectmethodService.findDetectmethodByPrimaryKey(detectmethod.getId()));

	}

	@RequestMapping(value = "/restGetDetectdetailDetect/{detectdetailId}/detect", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdetailDetect(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getDetect(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectdetailFeature/{detectdetailId}/feature", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdetailFeature(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectdetailUnit/{detectdetailId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdetailUnit(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetDetectdetailDetectmethod/{detectdetailId}/detectmethod", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetDetectdetailDetectmethod(@PathVariable Integer detectdetailId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				detectdetailDAO.findDetectdetailByPrimaryKey(detectdetailId).getDetectmethod(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListDetectdetails", method = RequestMethod.GET)
	@ResponseBody
	public Object restListDetectdetails() {
		return JSONObject.parse(cmiPsonService.toJsonString(detectdetailService.loadDetectdetails(), 2));
	}

	@RequestMapping(value = "/restListDetectdetailsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListDetectdetailsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = detectdetailPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Detectdetail> detectdetails = detectdetailDAO.findAllDetectdetails(startResult,
				cmiPagination.getPaginationSize());
		String detectdetailString = cmiPsonService.toPsonString(detectdetails, 2, cmiPagination);

		return JSONObject.parse(detectdetailString);
	}

	@RequestMapping("/detectdetailSelectBox")
	@ResponseBody
	public JSONObject detectdetailSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Detect":
				entitySet = detectService.loadDetectsByIdSet(searchValue);
				break;
			case "Feature":
				entitySet = featureService.loadFeaturesByIdSet(searchValue);
				break;
			case "Unit":
				entitySet = unitService.loadUnitsByIdSet(searchValue);
				break;
			case "Detectmethod":
				entitySet = detectmethodService.loadDetectmethodsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Detect":
				entitySet = detectDAO.findAllDetects((pageNumber - 1) * paginationSize, paginationSize);
				count = detectService.countDetects();
				break;
			case "Feature":
				entitySet = featureDAO.findAllFeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = featureService.countFeatures();
				break;
			case "Unit":
				entitySet = unitDAO.findAllUnits((pageNumber - 1) * paginationSize, paginationSize);
				count = unitService.countUnits();
				break;
			case "Detectmethod":
				entitySet = detectmethodDAO.findAllDetectmethods((pageNumber - 1) * paginationSize, paginationSize);
				count = detectmethodService.countDetectmethods();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Detect":
				entitySet = detectDAO.findDetectByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = detectService.countDetectsByName(queryword);
				break;
			case "Feature":
				entitySet = featureDAO.findFeatureByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = featureService.countFeaturesByName(queryword);
				break;
			case "Unit":
				entitySet = unitDAO.findUnitByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = unitService.countUnitsByName(queryword);
				break;
			case "Detectmethod":
				entitySet = detectmethodDAO.findDetectmethodByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = detectmethodService.countDetectmethodsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
